﻿using JT808Protocol.Abstracts;
using JT808Protocol.Models;
using JT808Protocol.Models.BodyParserStrategy.Location;
using JT808Protocol.Models.BodyParserStrategy.Others;
using System;
using System.Collections.Generic;
using System.Linq;

namespace JT808Protocol.Handlers
{
    /// <summary>
    /// 车辆定位信息处理
    /// </summary>
    public class LocationHandler : MsgHandlerBase
    {
        public override EnumMessageType[] handleTypes => new EnumMessageType[] { EnumMessageType.位置信息汇报, EnumMessageType.位置信息批量汇报 };

        public override JT808Package[] Execute(JT808Package reqPkg)
        {
            if (!handleTypes.Contains(reqPkg.Header.MessageType)) return null;

            var addtions = new List<ILocationAddition>();

            switch (reqPkg.Header.MessageType)
            {
                case EnumMessageType.位置信息汇报:
                    addtions.AddRange(((DrLocation_0x0200)reqPkg.Body).Additions);

                    break;

                case EnumMessageType.位置信息批量汇报:
                    foreach (var location in ((DrLocationBatchReport_0x0704)reqPkg.Body).BatchLocation)
                    {
                        addtions.AddRange(location.Additions);
                    }
                    break;
            }

            //处理报警
            var attachmentUploadBodies = new List<PrAlarmAttachmentUpload_0x9208>();
            foreach (var addition in addtions)
            {
                //主动安全报警类型
                if (addition.AdditionID == EnumLocationAddition.ADAS ||
                    addition.AdditionID == EnumLocationAddition.BSD ||
                    addition.AdditionID == EnumLocationAddition.DSM ||
                    addition.AdditionID == EnumLocationAddition.TPMS)
                {
                    //发送附件上传请求
                    var prAttachmentUpload = new PrAlarmAttachmentUpload_0x9208
                    {
                        AttachmentServerIP = AlarmAttachmentServerIP,
                        AttachmentServerIPLen = (byte)AlarmAttachmentServerIP.Length,
                        AttachmentServer_TcpPort = (ushort)AlarmAttachmentServerPort,
                        AlarmId = Guid.NewGuid().ToString("N"), //长度为32
                        AlarmLogo = addition.AlarmLogo.OriginalData
                    };
                    attachmentUploadBodies.Add(prAttachmentUpload);
                }
            }

            return MultiResult(reqPkg, EnumMessageType.附件上传指令, attachmentUploadBodies.ToArray());
        }
    }
}